package org.wz.complex.work.kit.db;

import org.wz.complex.work.bean.ColumnsMetadata;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public interface MetaKit {

    // 获取列
    public static List<ColumnsMetadata> getColumns(Connection connection, String tableTableName) throws Exception {

        List<ColumnsMetadata> list = new ArrayList<>();

        DatabaseMetaData metaData = connection.getMetaData();
        ResultSet columnsResultSet = metaData.getColumns(connection.getCatalog(), connection.getSchema(), tableTableName, "%");

        while (columnsResultSet.next()) {

            ColumnsMetadata build = ColumnsMetadata.builder().build();

            //  字段名称
            build.setColumnColumnName(columnsResultSet.getString("COLUMN_NAME"));

            //  字段类型字符串
            build.setColumnTypeName(columnsResultSet.getString("TYPE_NAME"));

            //  字段注释
            build.setColumnRemarks(columnsResultSet.getString("REMARKS"));

            // 字段长度
            build.setColumnColumnSize(columnsResultSet.getString("COLUMN_SIZE"));

            //  是否可为null,   0: 不能为null    1: 可以为null
            String nullable = columnsResultSet.getString("NULLABLE");
            build.setColumnNullable("0".equals(nullable) ? "n" : "y" );

            // 小数位数
            build.setColumnDecimalDigits(columnsResultSet.getString("DECIMAL_DIGITS"));

            // 是否自动递增
            String isAutoincrement = columnsResultSet.getString("IS_AUTOINCREMENT");
            build.setColumnIsAutoincrement("NO".equals(isAutoincrement) ? "n" : "y"  );

            // add
            list.add(build);

        }
        columnsResultSet.close();

        return list;
    }


}
